<?php

class API extends CoreController {

	private $listAPI;

	function __construct()
	{
		parent::__construct();
		$this->listAPI = self::listAPI();
	}

	public function responseData($status,$data)
	{
		$this->loadComponent('jsonComponent');
		echo jsonComponent::encodeData(array_merge(array('status'=>$status),$data));
		exit;
	}

	public function formatDataUTF8($data) {
   		return preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($data));
	}

	public function formatData($data,$key=null)
	{
		$dataFormat = array();
		foreach($data as $value){
			$dataFormat[(!empty($key) ? $key : "data")] = $value;
		}
		return $dataFormat;
	}

	public function validateMethod($attributes=array())
	{
		if($attributes['class'] == $attributes['currentClass'] && method_exists($attributes['currentClass'],$attributes['action'])){
			if(!empty($attributes['data'])){
				return array('error'=>false,'data'=>$attributes['data']);
			}else{
				$this->responseData(200,array('error'=>true,'message'=>'No items where found for API'));
			}
		}else{
			$this->responseData(500,array('error'=>true,'message'=>'The server encountered an error processing your request'));
		}
	}

	public function getPaginationURL($attrs)
	{
		return array(
			'first_page'=> ((int)$attrs['id'] >=4) ? CORE_API_URL.str_replace("::","/",$attrs['method'])."/1" : null,
			'previouse_page'=>((int)$attrs['id']>1) ? CORE_API_URL.str_replace("::","/",$attrs['method'])."/".($attrs['id']-1) : null,
			'next_page'=>((int)$attrs['id'] < (int)$attrs['last']) ? CORE_API_URL.str_replace("::","/",$attrs['method'])."/".($attrs['id']+1) : null,
			'last_page'=>CORE_API_URL.str_replace("::","/",$attrs['method'])."/".$attrs['last'],
		);
	}

	public function getMethod($var)
	{
		if(isset($var['api_name']) && isset($var['action'])) {
			if(!in_array($var['api_name'],$this->listAPI)){
				$this->responseData(404,array('error'=>true,'message'=>'API Not Found'));
			}else{
				if(class_exists($var['api_name'])){
					$classMethod = get_class_methods($var['api_name']);
					if(!in_array($var['action'],$classMethod)){
						$this->responseData(404,array('error'=>true,'message'=>'Method Not Found'));
					}else{
						if(isset($var['id']) && !empty($var['id']) && validate_variable($var['id'],'number')) {
							return array('class'=>$var['api_name'],'action'=>$var['action'],'id'=>$var['id']);
						}else if(!empty($var['id']) && validate_variable($var['id'],'number') == false){
							$this->responseData(500,array('error'=>true,'message'=>'Parameter id is missing'));
						}else{
							return array('class'=>$var['api_name'],'action'=>$var['action']);
						}
					}
				}else{
					$this->responseData(404,array('error'=>true,'message'=>'API Not Found'));
				}
			}
		}else{
			$this->responseData(500,array('error'=>true,'message'=>'The server encountered an error processing your request'));
		}
	}

}